package ac.java.utils;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AcDownLoad {
	public static HttpServletResponse getFsHttpResponse(String path,
			HttpServletResponse response, HttpServletRequest request) {

		long readSt = 0;
		long readEd = 0;
		long fileSize = 0;
		String fileName = null;

		try {

			// path是指欲下载的文件的路径。
			File dFs = new File(path);
			FileInputStream fis = new FileInputStream(path);

			// 取得文件名。
			fileName = dFs.getName();
			fileSize = dFs.length();
			readEd = fileSize - 1;

			// 清空response
			response.reset();
			response.setHeader("Accept-Ranges", "bytes");
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment;filename=\""
					+ new String(fileName.getBytes(), "ISO8859_1") + "\"");

			String rangeStr = request.getHeader("Range");

			if (rangeStr != null) {
				rangeStr = rangeStr.toLowerCase();

				// 若客户端传来Range，说明之前下载了一部分，设置206状态(SC_PARTIAL_CONTENT)
				response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
				rangeStr = rangeStr.split("=")[1];
				String[] rs = rangeStr.split("-");

				if (rs.length > 0) {
					readSt = Integer.parseInt(rs[0]);
					if (rs.length > 1) {
						readEd = Integer.parseInt(rs[1]);
						if (readEd <= 0 || readEd > fileSize) {
							readEd = fileSize - 1;
						}
					}
				}

				//System.out.println("请求:" + request.getHeader("Range"));
				// System.exit(0);
			}

			if (readSt > 0) {
				response.setHeader("Content-Range", "bytes " + readSt + "-"
						+ readEd + "/" + fileSize);
				//System.out.println("输出:Content-Range =" + "bytes " + readSt	+ "-" + readEd + "/" + fileSize);
				response.setHeader("Content-Length", "" + (readEd - readSt + 1));

				// 读取跳过
				// System.out.println("跳过:"+ readSt);
				fis.skip(readSt);
			} else {
				response.setHeader("Content-Range", "bytes " + readSt + "-"
						+ readEd + "/" + fileSize);
				response.setHeader("Content-Length", fileSize + "");
			}

			byte by[] = new byte[10240];
			OutputStream os = response.getOutputStream();

			int len = 0;
			while ((len = fis.read(by)) != -1) {
				os.write(by, 0, len);
			}

			fis.close();
			os.close();
		} catch (IOException ex) {
			// ex.printStackTrace();
		}

		return response;
	}

	public static Integer post(String urlAddress, Map paramMap,
			String fileSavePath) {
		return post(urlAddress, paramMap, fileSavePath, true);
	}

	public static Integer post(String urlAddress, Map paramMap,
			String fileSavePath, boolean isContinue) {
		File fs = new File(fileSavePath);
		
		fs.getParentFile().mkdirs();
		
		long fsLen = 0;
		if (fs.exists()) {
			if (isContinue) {
				fsLen = fs.length();
			} else {
				return -1;
			}
		}

		Integer rs = 0;
		URL url = null;
		HttpURLConnection httpurlconnection = null;
		try {
			url = new URL(urlAddress);
			httpurlconnection = (HttpURLConnection) url.openConnection();
			httpurlconnection.setDoInput(true);
			httpurlconnection.setDoOutput(true);

			httpurlconnection.setRequestMethod("POST");
			httpurlconnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			if (fsLen > 0) {
				httpurlconnection.setRequestProperty("RANGE", "bytes=" + fsLen
						+ "-");
			}

			String queryString = AcHttp.getQueryParam(paramMap);
			httpurlconnection.getOutputStream().write(queryString.getBytes());

			httpurlconnection.getOutputStream().flush();
			httpurlconnection.getOutputStream().close();
			int httpCode = httpurlconnection.getResponseCode();

			if (httpCode == 200 || httpCode == 206) {
				// 发送Cookie
				String cookie = httpurlconnection.getHeaderField("Set-Cookie");
				if (null != cookie && !cookie.equals("")) {
					httpurlconnection.setRequestProperty("Cookie", cookie);
				}

				// 输入流
				InputStream is = httpurlconnection.getInputStream();

				// 1K的数据缓冲
				byte[] bs = new byte[10240];
				// 读取到的数据长度
				int len;
				// 输出的文件流
				OutputStream os = new FileOutputStream(fileSavePath, true);
				// 开始读取
				while ((len = is.read(bs)) != -1) {
					os.write(bs, 0, len);
				}

				// 完毕，关闭所有链接
				os.close();
				is.close();

				rs = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			rs = -10;
		} finally {
			if (httpurlconnection != null) {
				httpurlconnection.disconnect();
			}
		}

		return rs;
	}

	public static void get(String urlString, String filename)
			throws Exception {
		// 构造URL
		URL url = new URL(urlString);
		// 打开连接
		URLConnection con = url.openConnection();
		// 输入流
		InputStream is = con.getInputStream();

		// 1K的数据缓冲
		byte[] bs = new byte[1024];
		// 读取到的数据长度
		int len;
		// 输出的文件流
		OutputStream os = new FileOutputStream(filename);
		// 开始读取
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		// 完毕，关闭所有链接
		os.close();
		is.close();
	}
}
